<template>
  <div class="search">
    <input v-focus v-model="value" />
    {{ searchList.filter((v) => v) }}

    <div class="box" style="margin-top: 60px">
      <template v-for="item in searchHistory">
        <span class="hot-item" :key="item">{{ item }}</span>
      </template>
    </div>
  </div>
</template>

<script>
import LayoutComponent from '@/layout/index.vue'
import { mapState } from 'vuex'
import { debounce } from 'lodash'
// 使用防抖 将历史记录放置在一个数组中
export default {
  components: { LayoutComponent },
  data() {
    return {
      value: '',
      searchHistory: ['热门', '小说', '五大', '轻', '人文'],
      handleChange: null,
    }
  },
  created() {
    // console.log('debounce:', debounce)
  },
  watch: {
    value(newVal) {
      if (this.handleChange) {
        this.handleChange(newVal)
      }
    },
  },
  mounted() {
    this.handleChange = debounce(this.onChange, 1000)
  },
  computed: {
    ...mapState(['list']),
    searchList() {
      return this.list.map((item) => {
        if (!this.value.length) {
          return null
        } else {
          if (item.title.includes(this.value)) {
            return item
          }
        }
      })
    },
  },
  methods: {
    onChange(val) {
      if (val.length) {
        // 去重
        if (this.searchHistory.indexOf(val) === -1) {
          if (this.searchHistory.length > 5) {
            this.searchHistory.shift()
          }
          this.searchHistory.push(val)
        }
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  flex-wrap: wrap;
}
.hot-item {
  margin: 5px;
  padding: 5px 10px;
  background: #ccc;
  border-radius: 10px;
  text-align: center;
}
</style>
